import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  constructor() {
    super({});
  }

  async onModuleInit() {
    await this.$connect();
    const offsetTime = 8 * 60 * 60 * 1000;
    const offsetKey = Symbol('key');
    this.$use(async (params, next) => {
      const setOffsetTime = (obj: any, offsetTime: number) => {
        if (obj === null || obj === undefined || obj[offsetKey] || typeof obj !== 'object') return;
        for (const key in obj) {
          if (obj[key] instanceof Date) {
            obj[key] = new Date(obj[key].getTime() + offsetTime);
          } else if (typeof obj[key] === 'object') {
            setOffsetTime(obj[key], offsetTime);
          }
        }
        obj[offsetKey] = true;
      };
      // 所有的查询都加上时间偏移量
      setOffsetTime(params.args, offsetTime);
      const res = await next(params);
      // 结果全都减去时间偏移量
      setOffsetTime(res, -offsetTime);
      return res;
    });
  }
}
